import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { VideoLibrary } from './videoLibrary.entity';
import DataBase from '../../config/database'
import { MultiImg } from '../multiImg/multiImg.entity';
import { TraceRelaTable } from '../traceRelaTable/traceRelaTable.entity';
import { MultiImgLibrary } from '../multiImgLibrary/multiImgLibrary.entity';
import { VideoEnum } from '../video/video.enum';
import { video_SubAppId_List } from 'src/setting';

@Injectable()
export class VideoLibraryService {
  constructor(
    @InjectRepository(VideoLibrary)
    private videoLibraryRepository: Repository<VideoLibrary>,
    @InjectRepository(TraceRelaTable)
    private traceRelaTableRepository: Repository<TraceRelaTable>,
    @InjectRepository(MultiImgLibrary)
    private multiImgLibraryRepository: Repository<MultiImgLibrary>,
  ) {}

  async Create(video: VideoLibrary, wx_user: string, multi_img?: MultiImg[], traceRelaTableList?: TraceRelaTable[]){
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let addVideo = new VideoLibrary()
      addVideo.video_id = video.video_id
      addVideo.video_cover = video.video_cover
      addVideo.video_url = video.video_url
      addVideo.video_ratio = video.video_ratio
      addVideo.wx_user = wx_user
      addVideo.create_time = new Date()
      addVideo.update_time = addVideo.create_time
      addVideo.ic_group = video.ic_group
      addVideo.trace_id = video.trace_id
      addVideo.type = video.type
      let videoResult = await this.videoLibraryRepository.createQueryBuilder(null, queryRunner)
        .insert()
        .into(VideoLibrary)
        .values(addVideo)
        .execute()
      if(!videoResult?.generatedMaps?.[0]?.id) {
        throw new Error('上传视频失败')
      }

      if(traceRelaTableList.length > 0){
        await this.traceRelaTableRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(TraceRelaTable)
          .values(traceRelaTableList)
          .execute()
      }
      //如果是长图,添加图片
      if(multi_img?.length > 0){
        let multiImgList = []
        multi_img.map(async (e:MultiImgLibrary) => {
          let addMutImg = new MultiImgLibrary()
          addMutImg.cover = e.cover
          addMutImg.create_time = new Date()
          addMutImg.img = e.img
          addMutImg.img_id = e.img_id
          addMutImg.video_id = videoResult.generatedMaps[0].id
          addMutImg.trace_id = e.trace_id
          multiImgList.push(addMutImg)
        })
        await this.multiImgLibraryRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(MultiImgLibrary)
          .values(multiImgList)
          .execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }

  }

  async findAll(wx_user: string, take: number, skip: number): Promise<{data: VideoLibrary[], total: Number}> {
    let result = await this.videoLibraryRepository.findAndCount({
      where:{wx_user: wx_user},
      skip: skip,
      take: take,
      order: {'update_time':'desc'}
    })
    let videoList:VideoLibrary[] = result[0]
    //查询图片
    const multi_img = await this.videoLibraryRepository.query(`
      select a.video_id,a.img
      from multi_img_library a
      inner join (
        select video_library.id from video_library
        where video_library.wx_user = ?
        limit ?,?
      ) as video_library on video_library.id = a.video_id
      order by a.cover desc,a.id asc
    `,[wx_user, skip, take])

    videoList.filter((e:any) => e.type == VideoEnum.image).map((e:any) => {
      e.multi_img = multi_img.filter(c => c.video_id == e.id).map(c => c.img)
      e.multi_img_count = e.multi_img.length
      if(e.multi_img_count === 0){
        e.multi_img = [e.video_cover]
      }
    })


    return {data:videoList, total: result[1]}
  }

  findOne(id: any): Promise<VideoLibrary> {
    return this.videoLibraryRepository.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.videoLibraryRepository.delete(id);
  }

  async create(videoLibrary: VideoLibrary): Promise<void> {
    await this.videoLibraryRepository.save(videoLibrary);
  }

   /**
   * 删除视频
   * @param id 
   * @returns 
   */
   async delete(id: number, wx_user: string, deleteResource: Function) : Promise<any> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    //查询视频详情
    let findVideo = await this.videoLibraryRepository.findOne({where:{id:id}})
    if(findVideo.wx_user != wx_user){
      return '此视频不属于你。'
    }
    //如果是多图，删除所有图片
    let multiImgList: MultiImg[] = []
    if(findVideo.type === VideoEnum.image){
      //查询所有图片
      multiImgList = await this.multiImgLibraryRepository.find({where:{video_id:findVideo.id}})
    }
    try {
      //删除一个视频
      await this.videoLibraryRepository.createQueryBuilder(null,queryRunner).delete().where({id:id}).execute()
      if(multiImgList.length > 0){
        //删除所有多图
        await this.multiImgLibraryRepository.createQueryBuilder(null,queryRunner).delete().where({video_id:id}).execute()
        //删除多图资源
        for(let i = 0; i < multiImgList.length; i++){
          await deleteResource(multiImgList[i].img_id, video_SubAppId_List.videolibrary)
        }
      }
      //删除云资源
      await deleteResource(findVideo.video_id, video_SubAppId_List.videolibrary)


      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
}
